package com.alinesno.cloud.initializr.starter.gateway.plugin;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.common.facade.mapper.entity.BaseEntity;
import com.alinesno.cloud.initializr.starter.entity.InitializrDbListEntity;
import com.alinesno.cloud.initializr.starter.service.IInitializrDbListService;
import com.alinesno.cloud.rest.gateway.adapter.plugins.TranslateCode;
import com.alinesno.cloud.rest.gateway.adapter.plugins.TranslatePlugin;

/**
 * 代码生成转换插件
 *
 * @author LiangJiaMing
 * @date 2021年9月23日
 */
@Component("genControllerCodeGenPlugin")
public class GenControllerCodeGenPlugin implements TranslatePlugin {

	private final String TABLE_SCHEMA = "tableSchema";

	@Autowired
	private IInitializrDbListService initializrDbListService;

	@Override
	public void translate(List<JSONObject> node, TranslateCode convertCode) {
		List<String> tableSchemaIds = this.extractIds(node, TABLE_SCHEMA);
		
		if(tableSchemaIds.size() == 0) {
			return ;
		}
		
		List<InitializrDbListEntity> initializrDbList = initializrDbListService.lambdaQuery()
				.in(InitializrDbListEntity::getDbName, tableSchemaIds).orderByDesc(BaseEntity::getAddTime).list();
		
		Map<String, InitializrDbListEntity> initializrDbMap = !initializrDbList.isEmpty()
				? initializrDbList.parallelStream().collect(
						Collectors.toMap(InitializrDbListEntity::getDbName, entity -> entity, (entity, old) -> entity))
				: Collections.emptyMap();

		node.forEach(jsonObject -> {
			String tableSchema = jsonObject.getString(TABLE_SCHEMA);
			jsonObject.put(TABLE_SCHEMA + LABEL_SUFFER,
					initializrDbMap.containsKey(tableSchema) ? initializrDbMap.get(tableSchema).getDbDesc() : "无");
		});

	}
}
